package com.aidong.carnival.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.aidong.carnival.controllers.concerns.PageUtil;
import com.aidong.carnival.dao.TalentDao;
import com.aidong.carnival.entity.Photo;
import com.aidong.carnival.entity.Talent;
import com.aidong.carnival.entity.Vote;
import com.aidong.carnival.entity.VotedTalent;
import com.aidong.carnival.service.TalentService;

@Service
public class TalentServiceImpl implements TalentService {

	@Autowired
	TalentDao talentDao;

	@Override
	public List<Talent> list(int cid, String type, int page) {
		return talentDao.list(cid, type, (page - 1) * PageUtil.pageSize, PageUtil.pageSize);
	}

	@Override
	public Talent findByIdongId(int carnivalId, int idongId) {
		return talentDao.findByIdongId(carnivalId, idongId);
	}

	@Override
	@Transactional
	public Talent apply(int carnivalId, int idongId, String type, String[] images, String description) {
		Talent talent = talentDao.findByIdongId(carnivalId, idongId);
		if (talent == null) {
			// 用户还未报名，添加报名
			talent = new Talent(carnivalId, idongId, type, images[0]);
			talentDao.create(talent);

		}
		List<Photo> pList = new ArrayList<Photo>();
		for (String imgUrl : images) {
			pList.add(new Photo(carnivalId, idongId, imgUrl, description));
		}
		talentDao.addPhotos(pList);
		return talent;
	}

	@Override
	@Transactional
	public void vote(Vote vote) {
		talentDao.vote(vote);
		talentDao.addVoteLog(vote);
	}

	@Override
	public int votedCount(int carnivalId, int idongId) {
		return talentDao.votedCount(carnivalId, idongId);
	}

	@Override
	public List<VotedTalent> selectVoted(int carnivalId, int idongId) {
		return talentDao.selectVoted(carnivalId, idongId);
	}

}
